package com.tai.network;

import org.junit.Test;

import java.io.*;

/**
 * The type File stream demo.
 *
 * @author taylor
 * @Description: 节点流  :      字符流 文本文件      字节流：非文本文件
 * @date 2021 /6/22 20:07
 */
public class FileStreamDemo {


    /**
     * 文件写出
     */
    @Test
    public void testFileReader(){
        File file = new File("temp/people.json");
        try (FileReader fr = new FileReader(file);){
            char[] buffer = new char[1024];
            int len;
            while ((len=fr.read(buffer) )!= -1){
                String s = new String(buffer, 0, len);
                System.out.println(s);
            }
            System.out.println(fr.read());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件写入
     */
    @Test
    public void testFileWrite() {
        FileWriter fw = null;

        try {
            File file = new File("temp/test.txt");
            fw = new FileWriter(file,false);
            fw.write("hello java!");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 字节流处理 复制demo
     */
    @Test
    public void testFileInputOutputStream(){
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            File srcFile = new File("temp/jvm.jpg");
            File descFile = new File("temp/taylor.jpg");

            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(descFile);

            byte[] buffer = new byte[5];
            int len;
            while ((len =fis.read(buffer)) != -1 ){
                fos.write(buffer,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
